// pages/type/type-search.js
const app = getApp();
const network = require("../../utils/network.js");
const util = require("../../utils/util.js");
const EARTH_RADIUS = 6378.137; //地球半径
const chooseLocationPlugin = requirePlugin('chooseLocation');
const layerId = 'f222c4950df9';
import Dialog from '@vant/weapp/dialog/dialog';

// 默认值
const setting = {
  skew: 0,
  rotate: 0,
  showLocation: true,
  showScale: false,
  enableZoom: true,
  enableScroll: true,
  enableRotate: true,
  showCompass: false,
  enable3D: false,
  enableOverlooking: false,
  enableSatellite: false,
  enableTraffic: false,
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    useColor: util.themeColor,

    cuForm: {
      isNew: false,
      customerIndex: -1,
      customerId: null,
      newCustomerName: '',
      buildingIds: [],
      mtCount: {},
      memo: ''
    },
    myCustomersPopShow: false,
    myCustomers: [],

    allMediaType: [],
    mtCan: [],

    mapCtx: null,
    mapOpenHeat: false,
    buildings: [],
    pointCount: 0,
    setting: setting,
    circles: [],
    markers: [],
    windowHeight: app.globalData.windowHeight,
    defaultLat: 31.78,
    defaultLng: 119.95,
    lat: 31.78,
    lng: 119.95,
    searchForm: {
      radius: null
    },
    class1: 'z1', //默认正面在上面
    class2: 'z2',
    showList: false,

    submitPopShow: false,

    searchTabActive: 'filter',

    distanceRadio: 0,
    distanceRadioShow: '',
    distanceData: [],

    areaCheckBox: [],
    areaCheckBoxShow: [],
    areaData: [],

    sourceBuilding2ndTypeCheckBox: {},
    sourceBuildingPriceCheckBox: {},
    sourceBuildingCheckInRateCheckBox: {},
    sourceBuildingYearCheckBox: {},

    filterDate: '',
    filterDateDefault: [],
    showFilterDate: false,
    filterDateStart: '',
    filterDateEnd: '',

    filterIndustryCollapseActiveName: [],
    filterIndustryRadio: null,
    filterIndustryRadioShow: '',
    filterIndustryData: [],

    sourceCheckBoxMainActiveIndex: 0,
    sourceCheckBoxActiveId: [],
    sourceCheckBoxShow: [],
    sourceData: [],
  },

  noop() {},

  submitNeed() {
    const isNew = !!this.data.cuForm.isNew;
    if (isNew && !this.data.cuForm.newCustomerName) {
      util.showToast('请输入新客户名称')
      return;
    }
    if (!isNew && !this.data.cuForm.customerId) {
      util.showToast('请选择客户')
      return;
    }

    let allNeed = 0;
    const keys = Object.keys(this.data.cuForm.mtCount || {}) || [];
    keys.forEach(key => {
      allNeed += parseInt(this.data.cuForm.mtCount['' + key] || 0)
    });
    if (allNeed <= 0) {
      util.showToast('请输入需求数量')
      return;
    }
    Dialog.confirm({
      title: '确认',
      message: '您确定要推送该需求？',
    }).then(() => {
      util.showLoading('提交中');
      network.POST({
        uri: app.api.submitCustomerNeed,
        params: {
          isNew: this.data.cuForm.isNew,
          customerId: this.data.cuForm.customerId,
          newCustomerName: this.data.cuForm.newCustomerName,
          buildingIds: (this.data.buildings || []).map(d => d.id),
          mtCount: this.data.cuForm.mtCount,
          memo: this.data.cuForm.memo,
          beginDate: this.data.filterDateStart,
          endDate: this.data.filterDateEnd
        },
        success: (res) => {
          this.onCloseSubmitPop();
          util.hideLoading();
          util.showToast('提交成功', 'success');
        },
        complete: () => {
          util.hideLoading();
        }
      })
    }).catch(() => {
      // on cancel
    });
  },

  showMyCustomersPop() {
    this.setData({
      myCustomersPopShow: true
    });
  },

  onChangeCuFormIsNew(event) {
    this.setData({
      'cuForm.isNew': event.detail
    })
  },

  onChangeNewCustomerName(event) {
    this.setData({
      'cuForm.newCustomerName': event.detail
    })
  },

  onConfirmCustomerId(event) {
    const {
      value,
      index
    } = event.detail;
    this.setData({
      'cuForm.customerIndex': index,
      'cuForm.customerId': value.id,
      myCustomersPopShow: false,
    })
  },

  onCancelCustomerId() {
    this.setData({
      myCustomersPopShow: false,
    })
  },

  onChangeNeedCount(event) {
    const {
      detail,
      target: {
        dataset: {
          item
        }
      }
    } = event;
    let count = 0;
    if (detail == null || detail === '') count = null;
    else if (parseInt(detail) > parseInt(item.can)) count = parseInt(item.can);
    else count = parseInt(detail);
    const key = 'cuForm.mtCount.' + item.id;
    this.setData({
      [key]: count
    })
  },

  onChangeMemo(event) {
    this.setData({
      'cuForm.memo': event.detail
    })
  },

  // 推送POp
  onShowSubmitPop() {
    this.sumMTCan();
    this.setData({
      submitPopShow: true,
    })
  },
  onCloseSubmitPop() {
    this.setData({
      submitPopShow: false,
    })
  },

  // 合计所有可用点位类型数
  sumMTCan() {
    let r = {};
    (this.data.buildings || []).forEach(b => {
      const keys = Object.keys(b.mt_can || {}) || [];
      keys.forEach(key => {
        let temp = r['' + key] || 0;
        r['' + key] = temp + parseInt(b.mt_can['' + key]);
      })
    })
    let list = [];
    (this.data.allMediaType || []).forEach(m => {
      if (r['' + m.id] > 0) list.push({
        id: m.id,
        name: m.name,
        can: r['' + m.id]
      });
    });
    this.setData({
      mtCan: list
    })
  },

  // 查询我跟进的客户
  initMyCustomers() {
    return network.GET({
      uri: app.api.myCustomerList,
      success: (res) => {
        let list = res.data;
        this.setData({
          myCustomers: list,
        })
      }
    })
  },

  // 查询所有媒体类型
  initAllMediaType() {
    return network.GET({
      uri: app.api.allMediaTypeList,
      success: (res) => {
        let list = res.data;
        this.setData({
          allMediaType: list,
        })
      }
    })
  },

  // 过滤筛选：距离
  onClickDistance(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      distanceRadio: name,
    }, function () {
      this.showCheckedDistance();
    });
  },
  initDistance() {
    // 查询所有距离选项
    return network.GET({
      uri: app.api.distanceList,
      success: (res) => {
        let list = res.data;
        this.setData({
          distanceRadio: 0,
          distanceRadioShow: list[0].name,
          distanceData: list,
        })
      }
    })
  },
  showCheckedDistance() {
    this.setData({
      distanceRadioShow: this.data.distanceData[parseInt(this.data.distanceRadio)].name,
    });
  },

  // 过滤筛选：区划
  onChangeArea(event) {
    this.setData({
      areaCheckBox: event.detail,
    }, function () {
      this.showCheckedArea()
    });
  },
  onToggleArea(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.area-checkboxes-${index}`);
    checkbox.toggle();
  },
  initCheckedArea() {
    // 查询常州所有行政区划
    network.GET({
      uri: app.api.areaList,
      success: (res) => {
        let list = res.data;
        this.setData({
          areaData: list
        })
      }
    })
  },
  showCheckedArea() {
    this.setData({
      areaCheckBoxShow: this.data.areaData.map((item, index) => {
        if (this.data.areaCheckBox.indexOf('' + index) !== -1) return item.name;
        else return '-1';
      }).filter(item => item !== '-1')
    });
  },

  // 过滤筛选-筛选-时间段
  onDisplayFilterDate() {
    this.setData({
      showFilterDate: true,
      filterDateDefault: this.data.filterDateDefault
    });
  },
  onCloseFilterDate() {
    this.setData({
      showFilterDate: false
    });
  },
  formatDateFilterDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  initFilterDate() {
    const now = new Date();
    this.setData({
      filterDate: `${this.formatDateFilterDate(now)} - ${this.formatDateFilterDate(now)}`,
      filterDateDefault: [now.getTime(), now.getTime()],
      filterDateStart: `${util.formatDate(now)}`,
      filterDateEnd: `${util.formatDate(now)}`,
    });
  },
  onConfirmFilterDate(event) {
    const [start, end] = event.detail;
    this.setData({
      showFilterDate: false,
      filterDate: `${this.formatDateFilterDate(start)} - ${this.formatDateFilterDate(end)}`,
      filterDateDefault: [start.getTime(), end.getTime()],
      filterDateStart: `${util.formatDate(start)}`,
      filterDateEnd: `${util.formatDate(end)}`,
    });
  },

  // 过滤筛选-筛选-行业
  onClickFilterIndustry(event) {
    const {
      name
    } = event.currentTarget.dataset;
    const isCurChecked = '' + this.data.filterIndustryRadio === '' + name;
    this.setData({
      filterIndustryRadio: (!!isCurChecked ? null : name),
    });
    this.showCheckedFilterIndustry();
  },
  initFilterIndustry() {
    // 查询所有行业
    network.GET({
      uri: app.api.industryList,
      success: (res) => {
        this.setData({
          filterIndustryData: res.data
        }, function () {
          this.setData({
            filterIndustryRadio: null,
            filterIndustryRadioShow: '',
          })
        })
      }
    })
  },
  onChangeFilterIndustryCollapseActive(event) {
    this.setData({
      filterIndustryCollapseActiveName: event.detail,
    });
  },
  showCheckedFilterIndustry() {
    this.setData({
      filterIndustryRadioShow: (this.data.filterIndustryRadio != null ? this.data.filterIndustryData[parseInt(this.data.filterIndustryRadio)].name : ''),
    });
  },

  // 过滤筛选：资源
  onClickSourceNav({
    detail = {}
  }) {
    this.setData({
      sourceCheckBoxMainActiveIndex: detail.index || 0,
    }, function () {
      this.showSource();
    });
  },
  onClickSourceItem({
    detail = {}
  }) {
    const {
      sourceCheckBoxActiveId
    } = this.data;
    const index = sourceCheckBoxActiveId.indexOf(detail.id);
    if (index > -1) {
      sourceCheckBoxActiveId.splice(index, 1);
    } else {
      sourceCheckBoxActiveId.push(detail.id);
    }
    this.setData({
      sourceCheckBoxActiveId
    }, function () {
      this.showSource();
    });
  },
  formatSourceItem(list) {
    return ((list || []).map(d => {
      return Object.assign({}, d, {
        id: d.type * 10000 + d.id,
        source_id: d.id,
        text: d.name
      })
    }));
  },
  initCheckedSource() {
    // 查询所有资源
    network.GET({
      uri: app.api.sourceList,
      success: (res) => {
        let list = (res.data || []).map((item, index) => {
          let temp = {
            id: item.id,
            text: item.name,
            use_slot: false,
            building2ndType_show: [],
            buildingPrice_show: [],
            buildingCheckInRate_show: [],
            buildingYear_show: [],
            children: []
          };
          if ((item.mpChildren || []).length > 0) {
            temp.children = this.formatSourceItem(item.mpChildren);
          } else {
            if ((item.mpABType || []).length > 0) temp.children = temp.children.concat(this.formatSourceItem(item.mpABType));
            if ((item.mpSpecs || []).length > 0) temp.children = temp.children.concat(this.formatSourceItem(item.mpSpecs));
          }
          if ((temp.children || []).length == 0) {
            // 无下级类型/分类、无AB面、无规格时，目前仅指“智能框”
            temp.use_slot = true;
            temp.building2ndType_show = this.formatSourceItem(item.building2ndType);
            temp.buildingCheckInRate_show = this.formatSourceItem(item.buildingCheckInRate);
            temp.buildingPrice_show = this.formatSourceItem(item.buildingPrice);
            temp.buildingYear_show = this.formatSourceItem(item.buildingYear);
          }
          const key1 = 'sourceBuilding2ndTypeCheckBox.' + index;
          const key2 = 'sourceBuildingPriceCheckBox.' + index;
          const key3 = 'sourceBuildingCheckInRateCheckBox.' + index;
          const key4 = 'sourceBuildingYearCheckBox.' + index;
          this.setData({
            [key1]: [],
            [key2]: [],
            [key3]: [],
            [key4]: [],
          })
          return temp;
        });
        this.setData({
          sourceData: list
        })
      }
    })
  },
  showSource() {
    let resultArr = [];
    // 项目类型
    const key_building_2nd_type = Object.keys(this.data.sourceBuilding2ndTypeCheckBox || {});
    (key_building_2nd_type || []).forEach(key => {
      const indexList = (this.data.sourceBuilding2ndTypeCheckBox['' + key] || []);
      if (indexList.length > 0) {
        const source = this.data.sourceData[parseInt(key)];
        resultArr.push('项目类型(' + source.text + ')：' + (indexList.map(ind => source.building2ndType_show[parseInt(ind)].text)).join(','));
      }
    });
    // 价格区间
    const key_building_price = Object.keys(this.data.sourceBuildingPriceCheckBox || {});
    (key_building_price || []).forEach(key => {
      const indexList = (this.data.sourceBuildingPriceCheckBox['' + key] || []);
      if (indexList.length > 0) {
        const source = this.data.sourceData[parseInt(key)];
        resultArr.push('价格区间(' + source.text + ')：' + (indexList.map(ind => source.buildingPrice_show[parseInt(ind)].text)).join(','));
      }
    });
    // 入住率
    const key_building_check_in_rate = Object.keys(this.data.sourceBuildingCheckInRateCheckBox || {});
    (key_building_check_in_rate || []).forEach(key => {
      const indexList = (this.data.sourceBuildingCheckInRateCheckBox['' + key] || []);
      if (indexList.length > 0) {
        const source = this.data.sourceData[parseInt(key)];
        resultArr.push('入住率(' + source.text + ')：' + (indexList.map(ind => source.buildingCheckInRate_show[parseInt(ind)].text)).join(','));
      }
    });
    // 交付年份
    const key_building_year = Object.keys(this.data.sourceBuildingYearCheckBox || {});
    (key_building_year || []).forEach(key => {
      const indexList = (this.data.sourceBuildingYearCheckBox['' + key] || []);
      if (indexList.length > 0) {
        const source = this.data.sourceData[parseInt(key)];
        resultArr.push('交付年份(' + source.text + ')：' + (indexList.map(ind => source.buildingYear_show[parseInt(ind)].text)).join(','));
      }
    });

    (this.data.sourceData || []).forEach(source => {
      const children = source.children || [];
      const checked = children.filter(c => this.data.sourceCheckBoxActiveId.indexOf(c.id) !== -1);
      if (checked.length > 0) {
        resultArr.push(source.text + '：' + (checked.map(item => item.text).join(',')));
      }
    });

    this.setData({
      sourceCheckBoxShow: resultArr
    });
  },
  // 过滤筛选-资源-项目二级类型
  onChangeSourceBuilding2ndType(event) {
    const {
      mainindex
    } = event.currentTarget.dataset;
    const key = 'sourceBuilding2ndTypeCheckBox.' + mainindex;
    this.setData({
      [key]: event.detail,
    }, function () {
      this.showSource()
    });
  },
  onToggleSourceBuilding2ndType(event) {
    const {
      mainindex,
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.source-building-2nd-type-checkboxes-${mainindex}-${index}`);
    checkbox.toggle();
  },
  // 过滤筛选-资源-项目价格区间
  onChangeSourceBuildingPrice(event) {
    const {
      mainindex
    } = event.currentTarget.dataset;
    const key = 'sourceBuildingPriceCheckBox.' + mainindex;
    this.setData({
      [key]: event.detail,
    }, function () {
      this.showSource()
    });
  },
  onToggleSourceBuildingPrice(event) {
    const {
      mainindex,
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.source-building-price-checkboxes-${mainindex}-${index}`);
    checkbox.toggle();
  },
  // 过滤筛选-资源-项目入住率
  onChangeSourceBuildingCheckInRate(event) {
    const {
      mainindex
    } = event.currentTarget.dataset;
    const key = 'sourceBuildingCheckInRateCheckBox.' + mainindex;
    this.setData({
      [key]: event.detail,
    }, function () {
      this.showSource()
    });
  },
  onToggleSourceBuildingCheckInRate(event) {
    const {
      mainindex,
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.source-building-check-in-rate-checkboxes-${mainindex}-${index}`);
    checkbox.toggle();
  },
  // 过滤筛选-资源-项目交付年份
  onChangeSourceBuildingYear(event) {
    const {
      mainindex
    } = event.currentTarget.dataset;
    const key = 'sourceBuildingYearCheckBox.' + mainindex;
    this.setData({
      [key]: event.detail,
    }, function () {
      this.showSource()
    });
  },
  onToggleSourceBuildingYear(event) {
    const {
      mainindex,
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.source-building-year-checkboxes-${mainindex}-${index}`);
    checkbox.toggle();
  },

  assembleSourceSpecial(sourceList, checkBoxName, innerShowName) {
    const keys = Object.keys(this.data['' + checkBoxName]) || [];
    keys.forEach(_mainIndex => {
      const mainIndex = parseInt(_mainIndex);
      const list = this.data['' + checkBoxName][mainIndex] || [];
      list.forEach(_innerIndex => {
        const innerIndex = parseInt(_innerIndex);
        sourceList.push(this.data.sourceData[mainIndex]['' + innerShowName][innerIndex]);
      })
    })
  },
  // 过滤筛选-查询
  assembleSearchParams(first) {
    let params = {
      positionLocation: {
        lat: this.data.lat,
        lng: this.data.lng,
      },
      beginDate: this.data.filterDateStart,
      endDate: this.data.filterDateEnd
    };
    if (!!first) return params;

    if (this.data.filterIndustryRadio != null) params.prohibitIndustryId = this.data.filterIndustryData[this.data.filterIndustryRadio].id;
    if (this.data.distanceData[this.data.distanceRadio].max != null) params.positionRadius = this.data.distanceData[this.data.distanceRadio].max;
    if ((this.data.areaCheckBox || []).length > 0) {
      let choosedArea = [];
      this.data.areaCheckBox.forEach(item => {
        choosedArea.push('' + this.data.areaData[parseInt(item)].id)
      })
      params.pcaList = choosedArea;
    }

    // 组装资源条件
    let sourceList = [];
    // 下级类型、分类、AB面、规格
    if ((this.data.sourceCheckBoxActiveId || []).length > 0) {
      (this.data.sourceData || []).forEach(top => {
        const children = top.children || [];
        children.forEach(item => {
          if (this.data.sourceCheckBoxActiveId.indexOf(item.id) != -1) sourceList.push(item);
        });
      })
    }
    // 特殊分类，项目类型、价格区间、入住率、交付年份
    this.assembleSourceSpecial(sourceList, 'sourceBuilding2ndTypeCheckBox', 'building2ndType_show');
    this.assembleSourceSpecial(sourceList, 'sourceBuildingPriceCheckBox', 'buildingPrice_show');
    this.assembleSourceSpecial(sourceList, 'sourceBuildingCheckInRateCheckBox', 'buildingCheckInRate_show');
    this.assembleSourceSpecial(sourceList, 'sourceBuildingYearCheckBox', 'buildingYear_show');

    params.sourceList = sourceList;

    return params;
  },
  doSearch() {
    this.redraw(this.data.lat, this.data.lng, false, false).then(() => {
      this.hideModal();
    })
  },
  searchBuilding(params) {
    return new Promise((resolve, reject) => {
      util.showLoading('加载中');
      network.POST({
        uri: app.api.searchBuilding,
        params,
        success: (res) => {
          let pointCount = 0;
          (res.data || []).forEach(item => {
            pointCount += (item.can || 0);
          });
          this.setData({
            buildings: res.data,
            pointCount: pointCount,
            'searchForm.radius': params.positionRadius || null
          }, function () {
            util.hideLoading();
            resolve();
          })
        },
        fail: (res) => {
          reject();
        }
      })
    })
  },

  redraw(lat, lng, toLocation, first) {
    const that = this
    return new Promise((resolve) => {
      that.setData({
        lat: lat,
        lng: lng,
        'searchForm.radius': !!first ? null : that.data.searchForm.radius
      }, async function () {
        await that.searchBuilding(that.assembleSearchParams(first));
        that.addCircles()
        that.getMarkers()
        if (!!toLocation) that.toLocation(true)
        resolve();
      })
    })
  },

  async onLoad() {
    const that = this

    that.initCheckedArea();
    that.initFilterDate();
    that.initFilterIndustry();
    that.initCheckedSource();
    that.initDistance();
    that.initMyCustomers();
    that.initAllMediaType();

    const location = chooseLocationPlugin.getLocation();
    if (!!location) {
      that.redraw(location.latitude, location.longitude, true, false)
    } else {
      const flag = await that.getLocationFlag()
      if (!flag) {
        console.log(1)
        that.redraw(that.data.defaultLat, that.data.defaultLng, false, true)
      } else {
        console.log(2)
        wx.showLoading({
          title: '定位中...',
          mask: true
        })
        const latLng = await that.getLatLng()
        console.log(latLng)
        wx.hideLoading({
          complete: (res) => {},
        })
        if (latLng) {
          console.log(3)
          that.redraw(latLng.lat, latLng.lng, false, true)
        } else {
          console.log(4)
          that.redraw(that.data.defaultLat, that.data.defaultLng, false, true)
        }
      }
    }
  },

  mapUpdated() {
    const that = this
    return new Promise((resolve) => {
      wx.hideLoading({
        complete: (res) => {},
      })
      that.setData({
        mapCtx: wx.createMapContext("myMap")
      }, function () {
        if (!that.data.showList) {
          setTimeout(function () {
            that.setData({
              showList: true
            })
          }, 1000)
        }
        resolve()
      })
    })
  },

  assembleExportParams() {
    let params = this.assembleSearchParams(false);
    params.building_ids = (this.data.buildings || []).map(d => d.id);
    return params;
  },
  exportEmptyExcel() {
    util.showLoading('下载中');
    network.POST({
      uri: app.api.exportData,
      params: this.assembleExportParams(),
      success: (res) => {
        if(!!res.data){
          wx.downloadFile({
            url: res.data,
            success: function (res) {
              util.hideLoading()
              //const filePath = res.tempFilePath;
              wx.shareFileMessage({
                filePath: res.tempFilePath,
                success(data) {
                  console.log('转发成功！！！',data)
                },
                fileName:'点位目录.xls',
                fail: console.error,
              })
              // wx.openDocument({
              //   filePath: filePath,
              //   fileType: 'xls',
              //   success: function (res) {
              //     console.log('打开文档成功')
              //   },
              //   fail: function (err) {
              //     console.log(err)
              //   }
              // })
            },
            fail: function (err) {
              util.hideLoading()
            }
          })
        }else{
          util.hideLoading()
          util.showToast('下载失败');
        }
      },
      fail: () => {
        util.hideLoading()
        util.showToast('下载失败');
      }
    })
  },

  rotateMapList(e) {
    let data = this.data;
    if (data.class1 == 'z1' && data.class2 == 'z2') {
      this.rotateRun('front', 'back', 'z2', 'z1');
    } else {
      this.rotateRun('back', 'front', 'z1', 'z2');
    }
  },
  rotateRun(a, b, c, d) {
    const that = this;
    that.setData({
      class1: a,
      class2: b,
    })
    setTimeout(function () {
      that.setData({
        class1: c,
        class2: d,
      })
    }, 1000);
  },

  /**
   * 获取楼盘
   */
  getMarkers() {
    this.refreshMarkers(this.data.buildings)
  },

  refreshMarkers(list) {
    const that = this
    let markers = [];
    if (list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        markers.push({
          id: item.id,
          width: 25,
          height: 25,
          latitude: item.lat,
          longitude: item.lng,
          iconPath: '/static/image/ad_empty.png',
          // callout: {
          //   anchorY: 0,
          //   content: item.name,
          //   color: '#FF929B',
          //   fontSize: 12,
          //   borderRadius: 3,
          //   bgColor: '#fff',
          //   padding: 5,
          //   display: 'ALWAYS',
          //   textAlign: 'center'
          // },
        })
      }
    }
    that.setData({
      markers: markers
    })
  },

  addCircles() {
    const that = this
    let circles = [];
    if (that.data.searchForm.radius) circles.push({
      latitude: that.data.lat,
      longitude: that.data.lng,
      radius: that.data.searchForm.radius,
      color: '#f37b1d',
      fillColor: '#fbbd0860',
      strokeWidth: 1
    })
    that.setData({
      circles: circles
    })
  },

  changeHeatMap() {
    const that = this
    if (that.data.mapOpenHeat) that.hideHeatMap()
    else that.showHeatMap()
  },

  showHeatMap() {
    const that = this
    if (that.data.mapCtx)
      that.data.mapCtx.addVisualLayer({
        layerId: layerId,
        interval: 15,
        zIndex: 30,
        success: function (msg) {
          console.log(msg)
          that.setData({
            mapOpenHeat: true
          })
        },
        fail: function (err) {
          console.log(err)
        },
        complete: function (msg) {
          console.log(msg)
        }
      })
  },

  hideHeatMap() {
    const that = this
    if (that.data.mapCtx)
      that.data.mapCtx.removeVisualLayer({
        layerId: layerId,
        success: function (msg) {
          console.log(msg)
          that.setData({
            mapOpenHeat: false
          })
        },
        fail: function (err) {
          console.log(err)
        },
        complete: function (msg) {
          console.log(msg)
        }
      })
  },

  openMapChooseLocationPlugin() {
    const that = this
    const key = app.globalData.mapKey; //使用在腾讯位置服务申请的key
    const referer = app.globalData.mapReferer; //调用插件的app的名称
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
    });
  },

  async toLocation(hasSetLocation) {
    const that = this
    if (!!hasSetLocation) {
      console.log(1)
      that.mapMoveTo()
    } else {
      console.log(2)
      const flag = await that.getLocationFlag()
      if (!!flag) {
        wx.showLoading({
          title: '定位中...',
          mask: true
        })
        const latLng = await that.getLatLng()
        wx.hideLoading({
          complete: (res) => {},
        })
        if (latLng) {
          that.setData({
            lat: latLng.lat,
            lng: latLng.lng
          }, function () {
            that.mapMoveTo()
          })
        } else {
          that.mapMoveTo()
        }
      }
    }
  },

  mapMoveTo() {
    const that = this
    if (that.data.mapCtx) {
      console.log(32)
      console.log(that.data.lat)
      console.log(that.data.lng)
      that.data.mapCtx.moveToLocation({
        latitude: that.data.lat,
        longitude: that.data.lng,
        success: function (res) {
          console.log(res)
        },
        fail: function (err) {
          console.log(err)
        }
      })
    }
  },

  getLatLng() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        highAccuracyExpireTime: 3000,
        success(res) {
          console.log(res)
          const {
            latitude,
            longitude
          } = res
          resolve({
            lat: latitude,
            lng: longitude
          })
        },
        fail(err) {
          console.log(err)
          resolve(null)
        }
      })
    })
  },

  getLocationFlag() {
    const that = this
    return new Promise(async (resolve, reject) => {
      let deviceFlag = true // 微信定位权限、手机定位开启
      let authFlag = true // 小程序定位权限
      let flag = false
      if (app.globalData.envVersion == 0) { // 开发只需要判断小程序权限
        authFlag = await that.checkMiniAuth()
        flag = authFlag
      } else {
        deviceFlag = await that.checkAuth()
        authFlag = await that.checkMiniAuth()
        flag = deviceFlag && authFlag
      }
      resolve(flag)
    })
  },

  // 检验微信的定位权限、设备定位的开启
  checkAuth() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfoAsync({
        success(res) {
          const {
            locationAuthorized,
            locationEnabled
          } = res
          if (!locationAuthorized) {
            util.showToast({
              icon: 'none',
              title: '请授予微信定位权限',
            })
          } else if (!locationEnabled) {
            util.showToast({
              icon: 'none',
              title: '请打开手机定位',
            })
          }
          resolve(
            locationAuthorized &&
            locationEnabled)
        }
      })
    })
  },

  // 检验小程序权限
  checkMiniAuth() {
    const that = this
    return new Promise((resolve, reject) => {
      let authResult = {
        location: null
      }

      function ownCallBack(authResult, resolve) {
        if (authResult.location != null) {
          resolve(authResult.location)
        }
      }
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                authResult.location = true
                ownCallBack(authResult, resolve)
              },
              fail() {
                authResult.location = false
                // util.showToast({
                //   icon: 'none',
                //   title: '请授权位置权限',
                // })
                that.setData({
                  modalName: 'DialogModalConfirmToSetPage'
                })
                ownCallBack(authResult, resolve)
              }
            })
          } else {
            authResult.location = true
            ownCallBack(authResult, resolve)
          }
        }
      })
    })
  },

  toSettingPage() {
    this.hideModal()
    wx.openSetting({
      success(res) {
        console.log(res.authSetting)
      }
    })
  },

  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },

  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  // 计算距离
  rad: function (d) {
    return d * Math.PI / 180.0;
  },
  getDistance: function (lng1, lat1, lng2, lat2) {
    var radLat1 = this.rad(lat1);
    var radLat2 = this.rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.rad(lng1) - this.rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) *
      Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 100000) / 100000;
    return s; //返回数值单位：公里
  },
})